package com.qr.backend.interceptor;

import com.qr.backend.mapper.UserMapper;
import com.qr.backend.response.AccountUserResponse;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author : jinxiaobo
 * @date : 2023年12月21日 22:29:02
 * @description : 请求进来之前拦截器
 */

import com.qr.backend.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthorizeInterceptor implements HandlerInterceptor {

    @Resource
    private UserMapper userMapper;

    /**
     * 在处理请求之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //所有的请求处理之前会
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        User user = (User) authentication.getPrincipal();
        String username = user.getUsername();
        AccountUserResponse accountUserResponse = userMapper.findAccountUserNameOrEmail(username);
        request.getSession().setAttribute("account", accountUserResponse);
        return true;
    }
}

